package com.holy.sh.module_base_mvp.helper.glide;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Looper;
import android.support.annotation.DrawableRes;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.holy.sh.module_base_mvp.R;
import com.holy.sh.module_base_mvp.constants.ConstantsApi;
import com.holy.sh.module_base_mvp.utils.LogUtils;


import java.io.File;
import java.math.BigDecimal;

import static com.bumptech.glide.request.RequestOptions.bitmapTransform;

/**
 * * Glide工具类
 */
public class GlideUtils {
    //默认加载
    public static void loadImageView(Context mContext, String path, ImageView mImageView) {
        RequestOptions options = new RequestOptions()
                .placeholder(R.mipmap.default_pic)
                .error(R.mipmap.default_pic)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .priority(Priority.HIGH);

        String path_img=ConstantsApi.BASE_IMG_URL + path ;
        LogUtils.i("path_img","",path_img);
        Glide.with(mContext).load(path_img).apply(options).into(mImageView);
        // Glide.with(mContext).load(path).apply(new RequestOptions().centerCrop()).into(mImageView);
    }

    public static void loadImageViewnotHttp(Context mContext, String path, ImageView mImageView) {
        RequestOptions options = new RequestOptions()
                .placeholder(R.mipmap.default_pic)
                .error(R.mipmap.default_pic)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .priority(Priority.HIGH);

       // String path_img=ConstantsApi.BASE_IMG_URL + path ;
        LogUtils.i("path_img","",path);
        Glide.with(mContext).load(path).apply(options).into(mImageView);
        // Glide.with(mContext).load(path).apply(new RequestOptions().centerCrop()).into(mImageView);
    }
    //加载圆形图片
    public static void loadRunImg(Context mContext, String path, ImageView mImageView, int radius) {
        RequestOptions options = new RequestOptions()
                .placeholder(R.mipmap.default_pic)
                .error(R.mipmap.default_pic)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .centerCrop()
                .priority(Priority.HIGH)
                .transform(new GlideRoundTransform(mContext,radius));

        Glide.with(mContext).load(path).apply(options).into(mImageView);

    }

    /**
     * 加载头像专用
     * @param mContext
     * @param path
     * @param mImageView
     */
    public static void loadHeadImg(Context mContext, String path, ImageView mImageView) {
        if (mContext instanceof Activity) {
            Activity activity = (Activity) mContext;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                if (activity.isDestroyed()) {
                    return;
                }
            }
        }
        Glide.with(mContext)
                .load(path)
                .apply(new RequestOptions()
                        .centerCrop().transform(new GlideRoundTransform(mContext,5))
                        .placeholder(R.mipmap.default_pic)
                        .error(R.mipmap.default_pic))
                .into(mImageView);
    } /**
     * 加载头像专用
     * @param mContext
     * @param path
     * @param mImageView
     */
    public static void loadHeadImgCircle(Context mContext, String path, ImageView mImageView) {
        Glide.with(mContext)
                .load(path)
                .apply(new RequestOptions()
                        .centerCrop()
                        .transform(new GlideCircleTransform())
                        .placeholder(R.mipmap.default_pic)
                        .error(R.mipmap.default_pic))
                .into(mImageView);
    }

    /**
     * glide加载图片
     *
     * @param view view
     * @param url  url
     */
    public static void display(ImageView view, String url) {
        displayUrl(view, url, R.mipmap.default_pic);
    }

    /**
     * glide加载图片
     *
     * @param view         view
     * @param url          url
     * @param defaultImage defaultImage
     */
    private static void displayUrl(final ImageView view, String url, @DrawableRes int defaultImage) {

        RequestOptions options = new RequestOptions()
                .centerCrop()
                .placeholder(R.mipmap.default_pic)
                .error(R.mipmap.default_pic)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .priority(Priority.HIGH);
        // 不能崩
        if (view == null) {
            //KLog.e("GlideUtils -> display -> imageView is null");
            return;
        }
        Context context = view.getContext();
        if (context instanceof Activity) {
            if (((Activity) context).isFinishing()) {
                return;
            }
        }

        try {
            Glide.with(context)
                    .load(url)
                    .apply(options)
                    .into(view)
                    .getSize((width, height) -> {
                        if (!view.isShown()) {
                            view.setVisibility(View.VISIBLE);
                        }
                    });


        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void displayNative(final ImageView view, @DrawableRes int resId) {

        RequestOptions options = new RequestOptions()
                .centerCrop()
                .placeholder(R.mipmap.default_pic)
                .error(R.mipmap.default_pic)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .priority(Priority.HIGH);
        if (view == null) {
          //  KLog.e("GlideUtils -> display -> imageView is null");
            return;
        }
        Context context = view.getContext();
        if (context instanceof Activity) {
            if (((Activity) context).isFinishing()) {
                return;
            }
        }

        try {
            Glide.with(context)
                    .load(resId)
                    .apply(options)
                    .into(view)
                    .getSize((width, height) -> {
                        if (!view.isShown()) {
                            view.setVisibility(View.VISIBLE);
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    //加载指定大小
    public static void loadImageViewSize(Context mContext, String path, int width, int height, ImageView mImageView) {
        //  Glide.with(mContext).load(path).override(width, height).into(mImageView);
    }

    //填充图片
    public static void loadImageCrop(Context mContext, String path, ImageView mImageView) {
        // Glide.with(mContext).load(path).centerCrop().diskCacheStrategy(DiskCacheStrategy.ALL).into(mImageView);
    }

    //设置加载中以及加载失败图片
    public static void loadImageView(Context mContext, String path, ImageView mImageView, int defaultImage, int errorImageView) {
        // Glide.with(mContext).load(path).placeholder(defaultImage).error(errorImageView).into(mImageView);
    }

    //设置加载中以及加载失败图片并且指定大小
    public static void loadImageView(Context mContext, String path, int width, int height, ImageView mImageView, int lodingImage, int errorImageView) {
        //   Glide.with(mContext).load(path).override(width, height).placeholder(lodingImage).error(errorImageView).into(mImageView);
    }

    //设置跳过内存缓存
    public static void loadImageViewCache(Context mContext, String path, ImageView mImageView) {
        // Glide.with(mContext).load(path).skipMemoryCache(true).into(mImageView);
    }

    /**
     * 设置下载优先级
     * 优先级说明
     * Priority.LOW
     * Priority.NORMAL
     * Priority.HIGH
     * Priority.IMMEDIATE
     */

    public static void loadImageViewPriority(Context mContext, String path, Priority priority, ImageView mImageView) {
        //  Glide.with(mContext).load(path).priority(priority).into(mImageView);
    }

    /**
     * 策略解说：
     * all:缓存源资源和转换后的资源
     * none:不作任何磁盘缓存
     * source:缓存源资源
     * result：缓存转换后的资源
     */

    //设置缓存策略
    public static void loadImageViewDiskCache(Context mContext, String path, ImageView mImageView) {
        // Glide.with(mContext).load(path).diskCacheStrategy(DiskCacheStrategy.ALL).into(mImageView);
    }

    /**
     * 设置加载动画
     * api也提供了几个常用的动画：比如crossFade()
     */
    public static void loadImageViewAnim(Context mContext, String path, int anim, ImageView mImageView) {
        //Glide.with(mContext).load(path).animate(anim).into(mImageView);
    }

    /**
     * 设置缩略图支持, 会先加载缩略图,然后加载全图
     * 默认为原图的1/10
     */
    public static void loadImageViewThumbnail(Context mContext, String path, ImageView mImageView) {
        loadImageViewThumbnail(mContext, path, 0.1f, mImageView);
    }

    /**
     * 设置缩略图:注意这里的图片会变小，设置好imageView ScaleType
     *
     * @param thumb 缩略图比例,值为0~1
     */
    public static void loadImageViewThumbnail(Context mContext, String path, float thumb, ImageView mImageView) {
        Glide.with(mContext).load(path).thumbnail(thumb).into(mImageView);
    }

    /**
     * 设置动态转换
     * api提供了比如：
     * centerCrop():均衡缩放头像,保持图像原始比例，图像位于视图中心
     * fitCenter():缩放头像，在视图中使图像居中
     */
    public static void loadImageViewCrop(Context mContext, String path, ImageView mImageView) {
        // Glide.with(mContext).load(path).centerCrop().into(mImageView);
    }

    public static void loadImageViewFit(Context mContext, String path, ImageView mImageView) {
        //  Glide.with(mContext).load(path).fitCenter().into(mImageView);
    }

    //设置动态GIF加载方式
    public static void loadImageViewDynamicGif(Context mContext, String path, ImageView mImageView) {
        //   Glide.with(mContext).load(path).asGif().into(mImageView);
    }

    //设置静态GIF加载方式:显示Gif的第一帧
    public static void loadImageViewStaticGif(Context mContext, String path, ImageView mImageView) {
        // Glide.with(mContext).load(path).asBitmap().into(mImageView);
    }

    /**
     * 加载圆形图片
     * 注意：Transformation可以在transform()中叠加使用，自行实现。
     */

    public static void loadCircleImage(final Context mContext, final String path, final ImageView imageView) {
        final RequestOptions requestOptions = new RequestOptions().error(R.mipmap.default_pic).placeholder(R.mipmap.default_pic);
        final RequestOptions requestOptions1 = bitmapTransform(new GlideCircleTransform());
        Glide.with(mContext).load(path).listener(new RequestListener<Drawable>() {
            @Override
            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                Glide.with(mContext).load(R.mipmap.default_pic).apply(requestOptions1).into(imageView);
                return true;
            }

            @Override
            public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                return false;
            }
        }).apply(requestOptions1).into(imageView);
    }

    /**
     * 加载圆角图片
     * 注意：Transformation可以在transform()中叠加使用，自行实现。
     */
    public static void loadRoundImage(final Context mContext, String path, final ImageView imageView) {

        RequestOptions requestOptions = new RequestOptions().error(R.mipmap.default_pic).placeholderOf(R.mipmap.default_pic).bitmapTransform(new GlideRoundTransform(mContext, 5));
        final RequestOptions requestOptions1 = new RequestOptions().bitmapTransform(new GlideRoundTransform(mContext, 5));
        Glide.with(mContext).load(path).listener(new RequestListener<Drawable>() {
            @Override
            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                Glide.with(mContext).load(R.mipmap.default_pic).apply(requestOptions1).into(imageView);
                return true;
            }

            @Override
            public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                return false;
            }
        }).apply(requestOptions1).into(imageView);


//        Glide.with(mContext).load(path).apply(requestOptions).into(imageView);
        // Glide.with(mContext).load(path).(new GlideRoundTransform(mContext,20)).diskCacheStrategy(DiskCacheStrategy.ALL).crossFade().into(imageView);
    }

    /**
     * 加载模糊图片
     */
    public static void loadBlurImage(Context mContext, String path, ImageView imageView) {
        // Glide.with(mContext).load(path).transform(new BlurTransformation(mContext)).into(imageView);
    }

    /**
     * 设置监听请求接口
     * 设置监听的用处 可以用于监控请求发生错误来源，以及图片来源是内存还是磁盘
     */
 /*   public static void loadImageViewListener(Context mContext, String path, ImageView mImageView, RequestListener<String, GlideDrawable> requestListener) {
        //Glide.with(mContext).load(path).listener(requestListener).into(mImageView);
    }*/

    //项目中有很多需要先下载图片然后再做一些合成的功能，比如项目中出现的图文混排

  /*  //设置要加载的内容
    public static void loadImageViewContent(Context mContext, String path, SimpleTarget<GlideDrawable> simpleTarget) {
       // Glide.with(mContext).load(path).centerCrop().into(simpleTarget);
    }*/

//    //清理磁盘缓存
//    public static void GlideClearDiskCache(Context mContext) {
//        //理磁盘缓存 需要在子线程中执行
//        Glide.get(mContext).clearDiskCache();
//    }

    //清理内存缓存
    public static void GlideClearMemory(Context mContext) {
        //清理内存缓存  可以在UI主线程中进行
        Glide.get(mContext).clearMemory();
    }

    // 获取Glide磁盘缓存大小
  /*  public static String getCacheSize(Context mContext) {
        try {
            return getFormatSize(getFolderSize(new File(mContext.getCacheDir() + "/" + ProjectGlideModule.GLIDE_CACHE_DIR)));
        } catch (Exception e) {
            e.printStackTrace();
            return "获取失败";
        }
    }

    // 清除Glide磁盘缓存，自己获取缓存文件夹并删除方法
    public static boolean clearCatchDisk(Context mContext) {
        return deleteFolderFile(mContext.getCacheDir() + "/" + ProjectGlideModule.GLIDE_CACHE_DIR , true);
    }*/

    // 清除图片磁盘缓存，调用Glide自带方法
    public static boolean GlideClearDiskCache(final Context mContext) {
        try {
            if (Looper.myLooper() == Looper.getMainLooper()) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Glide.get(mContext).clearDiskCache();
                    }
                }).start();
            } else {
                Glide.get(mContext).clearDiskCache();
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    // 清除Glide内存缓存
    public static boolean clearCacheMemory() {
        try {
            if (Looper.myLooper() == Looper.getMainLooper()) { //只能在主线程执行
               // Glide.get(App.getInstance()).clearMemory();
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    // 获取指定文件夹内所有文件大小的和
    private static long getFolderSize(File file) throws Exception {
        long size = 0;
        try {
            File[] fileList = file.listFiles();
            for (File aFileList : fileList) {
                if (aFileList.isDirectory()) {
                    size = size + getFolderSize(aFileList);
                } else {
                    size = size + aFileList.length();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }

    // 格式化单位
    private static String getFormatSize(double size) {
        double kiloByte = size / 1024;
        if (kiloByte < 1) {
            return size + "B";
        }
        double megaByte = kiloByte / 1024;
        if (megaByte < 1) {
            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "KB";
        }
        double gigaByte = megaByte / 1024;
        if (gigaByte < 1) {
            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "MB";
        }
        double teraBytes = gigaByte / 1024;
        if (teraBytes < 1) {
            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "GB";
        }
        BigDecimal result4 = new BigDecimal(teraBytes);
        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "TB";
    }

    // 按目录删除文件夹文件方法
    private static boolean deleteFolderFile(String filePath, boolean deleteThisPath) {
        try {
            File file = new File(filePath);
            if (file.isDirectory()) {
                File files[] = file.listFiles();
                for (File file1 : files) {
                    deleteFolderFile(file1.getAbsolutePath(), true);
                }
            }
            if (deleteThisPath) {
                if (!file.isDirectory()) {
                    file.delete();
                } else {
                    if (file.listFiles().length == 0) {
                        file.delete();
                    }
                }
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @param view
     * @param path
     */
    public static void show(ImageView view, String path) {
        RequestOptions options = new RequestOptions()
                .centerCrop()
                .placeholder(R.mipmap.default_pic)
                .error(R.mipmap.default_pic)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .priority(Priority.HIGH);
        if (view == null) {
            //KLog.e("GlideUtils -> display -> imageView is null");
            return;
        }
        Context context = view.getContext();
        if (context instanceof Activity) {
            if (((Activity) context).isFinishing()) {
                return;
            }
        }

        try {
            Glide.with(context)
                    .load(new File(path))
                    .apply(options)
                    .into(view)
                    .getSize((width, height) -> {
                        if (!view.isShown()) {
                            view.setVisibility(View.VISIBLE);
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 后台获取图片
     */

    /**
     * 自定义Target
     */
    /**
     * 自定义数据源:ModelLoader
     * 根据不同的要求请求不同尺寸不同质量的图片
     */
}
